package ru.alt22.visor.php.core.reflection;

import org.eclipse.php.internal.core.phpModel.phpElementData.PHPFunctionData;
import org.eclipse.php.internal.core.phpModel.phpElementData.PHPModifier;

public class ReflectionMethod {
	private ReflectionClass reflectionClass;
	private ReflectionClass classContainer;
	private PHPFunctionData phpMethod;

	public ReflectionMethod(ReflectionClass reflectionClass, PHPFunctionData phpMethod) {
		this(null, reflectionClass, phpMethod);
	}

	public ReflectionMethod(ReflectionClass reflectionClass, ReflectionClass classContainer, PHPFunctionData phpMethod) {
		if (null == reflectionClass) {
			reflectionClass = findDeclaringClass(classContainer, phpMethod);
		}
		this.reflectionClass = reflectionClass;
		this.classContainer = classContainer;
		this.phpMethod = phpMethod;
	}

	public ReflectionClass getReflectionClass() {
		return reflectionClass;
	}

	public ReflectionClass getDeclaringClass() {
		return classContainer; 
	}

	public String getName() {
		return phpMethod.getName();
	}

	public boolean isAbstract() {
		return PHPModifier.isAbstract(phpMethod.getModifiers());
	}
	
	public boolean isPublic() {
		return !isProtected() && !isPrivate();
	}
	
	public boolean isProtected() {
		return PHPModifier.isProtected(phpMethod.getModifiers());
	}
	
	public boolean isPrivate() {
		return PHPModifier.isPrivate(phpMethod.getModifiers());
	}

	public boolean isStatic() {
		return PHPModifier.isStatic(phpMethod.getModifiers());
	}

	public boolean isFinal() {
		return PHPModifier.isFinal(phpMethod.getModifiers());
	}

	private static ReflectionClass findDeclaringClass(ReflectionClass classContainer, PHPFunctionData phpMethod) {
		ReflectionClass result = classContainer;
		while (null != result) {
			PHPFunctionData[] methods = result.getClassData().getFunctions(); 
			for (int i = 0; i < methods.length; i++) {
				if (methods[i].getName() == phpMethod.getName()) {
					return result;
				}
			}
			result = result.getSupertype();
		}
		throw new RuntimeException("No method " + phpMethod.getName() + " in class " + classContainer.getName());
	}

}